package com.hwadee.property.controller.info;

import com.hwadee.property.dto.RepairsPersonal;
import com.hwadee.property.pojo.House;
import com.hwadee.property.pojo.Repair;
import com.hwadee.property.service.IHouseService;
import com.hwadee.property.service.IRepairService;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/repair")
@Api(tags = "报修-RepairController")
@CrossOrigin
public class RepairController {

    @Autowired
    private IRepairService repairService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/personal")
    @ApiOperation(value = "【业主】查询本人报修记录", notes = "返回当前账号个人的所有报修记录的列表")
    public AjaxResult getAllRepairsPersonal(@RequestHeader("Authorization") String token) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询报修记录信息
            List<RepairsPersonal> repairs = repairService.listByOwnerIdPersonal(userId);

            // 返回报修记录
            return AjaxResult.success(repairs);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询本人报修记录失败" + e.getMessage());
        }
    }

    @GetMapping("/property/page")
    @ApiOperation(value = "【物业】分页查询报修记录", notes = "分页查询报修记录，支持按照处理状态进行检索。处理状态分为“待处理、处理中、已完成”三个状态。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, defaultValue = "10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "processingStatus", value = "处理状态", required = false, dataType = "String", paramType = "query")
    })
    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "processingStatus", required = false) String processingStatus) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据小区ID分页查询报修记录信息
            return  getPage(token, current, size, userService.getById(userId).getCommunityId(), processingStatus);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询报修记录失败" + e.getMessage());
        }
    }

    @GetMapping("/page")
    @ApiOperation(value = "【管理员】分页查询报修记录", notes = "分页查询报修记录，支持按照处理状态进行检索。处理状态分为“待处理、处理中、已完成”三个状态。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, defaultValue = "10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "processingStatus", value = "处理状态", required = false, dataType = "String", paramType = "query")
    })
    public AjaxResult getPage(@RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "communityID", required = false) Long communityID,
            @RequestParam(value = "processingStatus", required = false) String processingStatus) {

        PageResult<Repair> pageResult = repairService.getPage(current, size, communityID, processingStatus);
        return AjaxResult.success(pageResult);
    }

    @GetMapping("/house/{houseId}")
    @ApiOperation(value = "【管理员】根据房屋 ID 查询报修记录", notes = "根据房屋 ID 查询相关的报修记录")
    public AjaxResult getRepairsByHouseId(@RequestHeader("Authorization") String token, @ApiParam(value = "房屋 ID", required = true) @PathVariable Long houseId) {
        List<Repair> repairs = repairService.listByHouseId(houseId);
        return AjaxResult.success(repairs);
    }

    @PostMapping("/personal/post/{houseID}")
    @ApiOperation(value = "【业主】申请报修", notes = "创建一个新的报修记录")
    public AjaxResult addRepairPersonal(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "报修房屋 ID", required = true) @PathVariable Long houseID,
            @ApiParam(value = "报修内容详情", required = true) @RequestParam String content,
            @ApiParam(value = "期望报修时间", required = false) @RequestParam(required = false) String date) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // Validate date format if provided
            List<House> houses = houseService.listByOwnerId(userId);
            boolean flag = false;
            for (House i : houses) {
                System.out.println(i.getId());
                if (Objects.equals(i.getId(), houseID)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return AjaxResult.fail("名下没有该房屋，无法报修！");
            }

            return  addRepair(token, houseID, content, date);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("添加报修记录失败");
        }
    }

    @PutMapping("/property/update")
    @ApiOperation(value = "【物业】处理报修", notes = "物业根据报修 ID 对报修记录进行处理反馈。状态有：待处理、处理中、已完成、已取消")
    public AjaxResult updateRepairStatus(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "报修 ID", required = true) @RequestParam Long repairId,
            @ApiParam(value = "新状态", required = false) @RequestParam String status,
            @ApiParam(value = "处理反馈", required = false) @RequestParam String feedback) {
            // 如果token为空，返回错误
            if (token == null || token.isEmpty()) {
                return AjaxResult.fail("未授权, token 为空");
            }

            try {
                // 从token中解析出用户ID
                Long userId = jwtUtil.getUserId(token);

                Repair repair = new Repair();
                repair.setId(repairId);
                repair.setProcessingStatus(status);
                repair.setFeedBack(feedback);
                if (status.equals("处理中")) repair.setStartDate(DateUtil.dateToString(new Date()));
                repair.setHandlerId(userId);
                if (status.equals("已完成")) repair.setCompletionDate(DateUtil.dateToString(new Date()));
                boolean success = repairService.updateById(repair);
                return success ? AjaxResult.success() : AjaxResult.fail("处理报修失败");
            } catch (Exception e) {
                // token解析异常或其他异常，返回失败
                return AjaxResult.fail("token解析异常或其他异常，处理报修失败");
            }
    }


    @PostMapping("/post/{houseID}")
    @ApiOperation(value = "【管理员】添加新的报修记录", notes = "创建一个新的报修记录")
    public AjaxResult addRepair(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "报修房屋 ID", required = true) @PathVariable Long houseID,
            @ApiParam(value = "报修内容详情", required = true) @RequestParam String content,
            @ApiParam(value = "期望报修时间", required = false) @RequestParam(required = false) String date) {

        // Validate date format if provided
        if (date != null && !date.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            return AjaxResult.fail("日期格式不正确，请使用格式：yyyy-MM-dd");
        }

        Repair repair = new Repair();
        repair.setHouseId(houseID);
        repair.setRepairContent(content);
        repair.setRepairDate(date);
        boolean success = repairService.save(repair);
        return success ? AjaxResult.success() : AjaxResult.fail("添加报修记录失败");
    }

    @GetMapping("/get/{repairId}")
    @ApiOperation(value = "【管理员】根据 ID 查询单个报修记录", notes = "根据报修 ID 查询单个报修记录")
    public AjaxResult getRepairById(@RequestHeader("Authorization") String token, @ApiParam(value = "报修 ID", required = true) @PathVariable Long repairId) {
        Repair repair = repairService.getById(repairId);
        List<Repair> repairs = new ArrayList<>();
        repairs.add(repair);
        return repair != null ? AjaxResult.success(repairs) : AjaxResult.fail("报修记录未找到");
    }

    @PutMapping("/cancel/{repairId}")
    @ApiOperation(value = "【业主】取消报修", notes = "根据报修 ID 取消报修记录")
    public AjaxResult deleteRepair(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "报修 ID", required = true) @PathVariable Long repairId) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            List<Repair> repairs = repairService.listByOwnerId(userId);
            boolean flag = false;
            for (Repair i : repairs){
                if (i.getId().equals(repairId)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return AjaxResult.fail("没有该报修记录，无法取消！");
            }
            Repair repair = new Repair();
            repair.setId(repairId);
            repair.setProcessingStatus("已取消");
            boolean success = repairService.updateById(repair);
            return success ? AjaxResult.success() : AjaxResult.fail("取消报修失败");
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("token解析异常或其他异常，处理报修失败");
        }
    }
}
